package com.wectrls.config.handle;

import com.wectrls.common.CommonVO;
import com.wectrls.config.exceptiom.BindingResultHasFieldErrorsException;
import com.wectrls.config.exceptiom.CommonException;
import com.wectrls.enums.RESPONSE_ENUM;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

/**
 * @Package com.styles.codingstyle.Handle
 * @Description: 统一异常处理
 * @Author 陈建
 */
@ControllerAdvice
public class ExceptionHandle {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    //拦截所有异常
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonVO<Object> exceptionHandle(Exception e) {
        logger.error("拦截到异常信息：{}", e.getMessage());
        //处理所有抛出的通用自定义异常
        CommonVO<Object> commonVO = new CommonVO<>(RESPONSE_ENUM.FAIL_500.getCode(), e.getMessage());
        if (e instanceof CommonException) {
            commonVO.setCode(((CommonException) e).getCode());
            commonVO.setMessage(e.getMessage());
        }
        if (e instanceof MethodArgumentTypeMismatchException) {
            MethodArgumentTypeMismatchException methodArgumentTypeMismatchException = (MethodArgumentTypeMismatchException) e;
            String name = methodArgumentTypeMismatchException.getName();
            String value = (String) methodArgumentTypeMismatchException.getValue();
            Class<?> requiredType = methodArgumentTypeMismatchException.getRequiredType();
            commonVO.setCode(RESPONSE_ENUM.FAIL_500.getCode());
            commonVO.setMessage("请求参数异常," + name + ":" + value + "不能转换成" + requiredType.getSimpleName());
        }
        if (e instanceof NumberFormatException) {
            commonVO.setCode(RESPONSE_ENUM.FAIL_500.getCode());
            commonVO.setMessage("数据转换异常");
        }
        if (e instanceof BindingResultHasFieldErrorsException) {
            commonVO.setCode(((BindingResultHasFieldErrorsException) e).getCode());
            commonVO.setMessage(e.getMessage());
            commonVO.setData(((BindingResultHasFieldErrorsException) e).getErrorMsg());
        }
        return commonVO;
    }

}
